package com.xhs.hawaii.configuration;

import com.xhs.hawaii.common.SsoService;
import com.xhs.hawaii.framework.AuthenticationFilter;
import com.xhs.hawaii.framework.WebPattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;

import java.io.InputStream;

/**
 * @author tangchuang
 * @version 1.0
 * @since 2018/1/25
 */
@Slf4j
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private SsoService ssoService;

    private String[] ignoreUrls;

    @Override
    public void configure(WebSecurity web) throws Exception {
        init();
        web.ignoring().antMatchers(ignoreUrls);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        init();
        http.addFilterBefore(new AuthenticationFilter(ssoService), BasicAuthenticationFilter.class);
    }


    public void init() {
        try (InputStream input = getClass().getClassLoader().getResourceAsStream("web-pattern.yaml")) {
            Constructor constructor = new Constructor(WebPattern.class);
            TypeDescription webPatternsDescription = new TypeDescription(WebPattern.class);
            webPatternsDescription.putListPropertyType("antPatterns", String.class);
            constructor.addTypeDescription(webPatternsDescription);
            Yaml yaml = new Yaml(constructor);
            WebPattern webPatterns = (WebPattern) yaml.load(input);
            ignoreUrls = webPatterns.getAntPatterns().toArray(new String[0]);
        } catch (Exception e) {
            log.error("parse web-pattern.yaml error", e);
        }

    }
}
